﻿using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.JavascriptBinding;
using CefSharp.WinForms;
using 浏览器客户端.Helper;
using 浏览器客户端.Models.Model;
using 浏览器客户端.Script;

namespace 浏览器客户端
{
    public partial class MainWindow : Form
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Init();
        }

        private ChromiumWebBrowser WebBrowser { get; set; }

        public void Init()
        {
            //取消边框
            this.FormBorderStyle = FormBorderStyle.None;
            //最大化
            this.WindowState = FormWindowState.Maximized;
            //加载本地配置文件
            var config = Common.LoadConfig<LocalConfig>();
            if (config == null) config = new LocalConfig();
            if (config.Server.IsNullOrWhiteSpace() || config.Web.IsNullOrWhiteSpace())
            {
                Common.SaveConfig(config);
                MessageBox.Show(Properties.Resources.CheckConfig);
                return;
            }
            Config.Local = config;
            var settings = new CefSettings
            {
                Locale = "zh-CN"
            };
            //关闭缩放和媒体
            settings.CefCommandLineArgs.Add("enable-media-stream", "1");
            settings.CefCommandLineArgs.Add("disable-pinch", "1");
            Cef.Initialize(settings);
            CefSharpSettings.ConcurrentTaskExecution = true;
            //置顶
#if !DEBUG
            TopMost = true;
#endif
            //创建浏览器
            WebBrowser = new ChromiumWebBrowser(config.Web)
            {
                LifeSpanHandler = new DisableNewWindowHandler(),
                MenuHandler = new DisableMenuHandler(),
                Dock = DockStyle.Fill
            };
            //允许跨域
            WebBrowser.BrowserSettings.WebSecurity = CefState.Disabled;
            //浏览器注入对象
            WebBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            WebBrowser.JavascriptObjectRepository.NameConverter = new CamelCaseJavascriptNameConverter();
            //日志
            WebBrowser.JavascriptObjectRepository.Register("Logger", new LogScript(), true, BindingOptions.DefaultBinder);
            //身份证读卡器
            WebBrowser.JavascriptObjectRepository.Register("IdCardReader", new IdCardReaderScript(), true, BindingOptions.DefaultBinder);
            //IC卡读卡器
            WebBrowser.JavascriptObjectRepository.Register("IcCardReader", new IcCardReaderScript(), true, BindingOptions.DefaultBinder);
            //常用函数
            WebBrowser.JavascriptObjectRepository.Register("Common", new CommonScript(), false, BindingOptions.DefaultBinder);
            //启动扫码枪监听程序
            var scanner = new ScannerHook();
            scanner.ScannerEvent += ScannerEventListener;
            scanner.Start();
            //加载浏览器
            Controls.Add(WebBrowser);
#if DEBUG
            Task.Run(async() =>
            {
                await Task.Delay(3000);
                WebBrowser.ShowDevTools();
            });
#endif
        }

        /// <summary>
        /// 向浏览器发送扫码枪事件
        /// 请在浏览器中监听scanner_event事件
        /// 示例:
        /// document.addEventListener("scanner_event", (ev) => {
        ///     let code = ev.detail.code;
        /// });
        /// </summary>
        /// <param name="code"></param>
        private void ScannerEventListener(ScannerHook.ScanerCodes code)
        {
            Task.Run(() =>
            {
                WebBrowser.GetBrowser().MainFrame.ExecuteJavaScriptAsync($"document.dispatchEvent(new CustomEvent('scanner_event', {{ detail: {{ code: '{code.Result.Trim()}' }} }}));");
            });
        }
    }
}
